<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               title="物联信息"
               :modal="false"
               class="user-dialog add-or-updata"
               width="50%"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="dataForm"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="dataForm"
               label-position="left"
               @keyup.enter.native="dataFormSubmitHandle()"
               label-width="80px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="所属网关"
                          prop="gateway">
              <el-select v-model="dataForm.gateway"
                         clearable
                         style="width:100%"
                         placeholder="请选择所属网关">
                <el-option v-for="item in gatewayList"
                           :key="item.id"
                           :label="item.deviceId + '(' + item.name + ')'"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通信协议"
                          prop="agreement">
              <el-select v-model="dataForm.agreement"
                         clearable
                         style="width:100%"
                         placeholder="请选择设备类型">
                <el-option v-for="item in agreementList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="dataForm.agreement === 1">
        <div style="display:flex;justify-content: space-between">
          <div>点位表</div>
          <div>
            <el-button type="primary"
                       plain
                       @click="addRow()">添加一行</el-button>
          </div>
        </div>
        <table-template :loading='dataListLoading'
                        :fieldManagement='false'
                        :index='true'
                        :dataList='dataList'>
          <el-table-column prop="address"
                           label="变量地址"
                           min-width="100"
                           align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.address"
                               controls-position="right"
                               style="width: 100%"
                               :min="0"
                               :max="999999999"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="marks"
                           label="描述"
                           min-width="100"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.marks"
                        maxlength="50"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="length"
                           label="长度"
                           min-width="100"
                           align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.length"
                               controls-position="right"
                               :min="0"
                               style="width: 100%"
                               :max="999999999"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="power"
                           label="倍率"
                           min-width="100"
                           align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.power"
                               controls-position="right"
                               :precision="2"
                               style="width: 100%"
                               :step="0.1"
                               :max="999999999.99"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="purpose"
                           label="用途"
                           min-width="120"
                           align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.purpose"
                         clearable
                         @change="onchange(scope.row.purpose)"
                         @clear="onClear"
                         style="width:100%"
                         placeholder="请选择用途">
                <el-option v-for="item in purposeList"
                           :key="item.id"
                           :disabled="purposeList1.includes(item.id)"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :label="$t('handle')"
                           fixed='right'
                           header-align='center'
                           align='center'
                           width='80'>
            <template slot-scope='scope'>
              <el-button type='text'
                         size='small'
                         class='danger'
                         @click='deleteRow(scope.row)'>{{ $t('delete')}}</el-button>
            </template>
          </el-table-column>
        </table-template>
      </div>
      <template slot="footer">
        <el-button @click="closeDialog()">{{ $t("cancel") }}</el-button>
        <el-button type="primary"
                   :loading="dataListLoading"
                   @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import tableTemplate from '@/components/table-template'
export default {
  mixins: [mixinViewModule, minFormValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        deleteImgURL: '/system/oss/delete',
        getDataListURL: '', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addURL: 'tb/device/insertDevice', // 添加或修改接口，API地址
        updateURL: 'tb/device/updateDevice', // 添加或修改接口，API地址
        getDataInfoURL: '', // 数据详情，API地址
        deleteURL: '', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      visible: false,
      dataForm: {
        gateway: '',
        agreement: 1
      },
      agreementList: [{ id: 1, name: 'Modbus-TCP' },
        { id: 2, name: 'Modbus-RTU' }],
      gatewayList: [],
      purposeList: [{ // 原始数据
        id: 1, name: '读表', disabled: false
      }, {
        id: 2, name: '开关', disabled: false
      }],
      purposeList1: []
    }
  },
  components: { tableTemplate },
  mounted () {
  },
  methods: {
    init (data) {
      this.dataForm.id = data.id
      this.dataForm.agreement = data.agreement
      this.dataForm.gateway = data.gateway
      this.$nextTick(() => {
        if (this.dataForm.id) {
          this.$http.get('tb/device/getGateWayDeviceList').then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.gatewayList = res.data
          })
          let url = `tb/device/getIOTInformation?id=` + this.dataForm.id
          this.$http.get(url).then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.dataList = res.data
            this.dataList.forEach(item => {
              if (item.purpose) {
                this.purposeList1.push(item.purpose)
              }
            })
          })
        }
      })
      this.visible = true
    },
    onClear () {
      this.purposeList1 = []
      this.dataList.forEach(item => {
        if (item.purpose) {
          this.purposeList1.push(item.purpose)
        }
      })
    },
    onchange (val) {
      this.purposeList1.push(val)
    },
    // 删除行
    deleteRow (_row) {
      this.dataList.forEach((value, index, array) => {
        if (value.id === _row.id) {
          array.splice(index, 1)
        }
      })
    },
    // 新增行
    addRow () {
      this.dataList.push({
        did: this.dataForm.id,
        address: '',
        marks: '',
        power: '',
        length: '',
        purpose: ''
      })
    },
    closeDialog () {
    //   this.$refs.dataForm.resetFields()
      this.dataForm.agreement = 1
      this.dataForm.gateway = ''
      this.purposeList1 = []
      this.$emit('callBack')
      this.visible = false
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            let arr = {}
            arr.data = {}
            arr.data.id = this.dataForm.id
            arr.data.hydroPowerInfo = {}
            arr.data.hydroPowerInfo.agreement = this.dataForm.agreement
            arr.data.hydroPowerInfo.gateway = this.dataForm.gateway
            arr.data.hydroPowerInfo.modBusTcpInfo = []
            if (this.dataForm.agreement === 1) {
              for (let i = 0; i < this.dataList.length; i++) {
                if (!this.dataList[i].address && !this.dataList[i].marks && !this.dataList[i].power && !this.dataList[i].length) {
                  // array.splice(index, 1)
                  return this.$message.warning('变量地址/描述/地址长度/倍率不能为空,请确认后重试')
                }
              }
              arr.data.hydroPowerInfo.modBusTcpInfo = this.dataList
            }
            this.$http.put('tb/device/updateIOTInformation', arr).then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message.success('保存成功')
              this.closeDialog()
            })
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    )
  }
}
</script>

<style lang="scss" scoped>
</style>
